<template>
    <div>
        <a-form layout="inline"
                :model="searchData"
                style="margin: 10px 0">
            <a-form-item>
                <a-input v-model:value="searchData.name" placeholder="用户名"></a-input>
            </a-form-item>
            <a-form-item>
                <a-select
                        ref="select"
                        v-model:value="searchData.officeId"
                        placeholder="所属机构"
                        style="width: 300px"
                        :options="officeList"
                        :field-names="{label:'name',value:'id'}"
                ></a-select>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="load(1)">搜索</a-button>
            </a-form-item>
            <a-form-item>
                <a-button type="default" @click="rest">重置</a-button>
            </a-form-item>
        </a-form>
        <a-button type="primary" style="margin-bottom: 10px"
                  @click="openModal({password:'123'})">
            新增
        </a-button>
        <a-table :dataSource="userList"
                 :columns="columns"
                 :pagination="pagination"
                 @change="handlerChange"
                 bordered>
            <template #headPicture="{text,record}">
                <img :src="text" v-if="text" style="width: 50px;height: 50px;border-radius: 50%"/>
                <img src="https://lyj-mall-bucket.oss-cn-guangzhou.aliyuncs.com/20230129/default.png" v-else
                     style="width: 50px;height: 50px;border-radius: 50%"/>
            </template>
            <template #userType="{text,record}">
                {{text == 0 ? '普通用户' : '系统管理员'}}
            </template>
            <template v-slot:action="{text,record}">
                <a-space>
                    <a-button type="primary" ghost @click="openRoleModal(record.sysRoles,record.id)">担任角色</a-button>
                    <a-button type="primary" @click="openModal(record)">编辑</a-button>
                    <a-popconfirm
                            title="删除数据无法恢复，请确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-modal v-model:visible="visible" title="新增或编辑" @ok="handleOk">
            <a-form v-model="user"
                    :label-col="{ span: 8 }">
                <a-form-item label="账号">
                    <a-input v-model:value="user.username" :disabled="user.id"></a-input>
                </a-form-item>
                <a-form-item label="用户名">
                    <a-input v-model:value="user.name"></a-input>
                </a-form-item>
                <a-form-item label="所属机构">
                    <a-select
                            ref="select"
                            v-model:value="user.officeId"
                            placeholder="请选择"
                            :options="officeList"
                            :field-names="{label:'name',value:'id'}"
                    ></a-select>
                </a-form-item>
                <a-form-item label="用户类型">
                    <a-radio-group v-model:value="user.userType">
                        <a-radio :value="'0'">普通</a-radio>
                        <a-radio :value="'1'">系统管理员</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="电话号码">
                    <a-input v-model:value="user.phone"></a-input>
                </a-form-item>
                <a-form-item label="手机号码">
                    <a-input v-model:value="user.mobile"></a-input>
                </a-form-item>

            </a-form>
        </a-modal>
        <a-modal v-model:visible="roleModalVisible" title="分配角色" @ok="handleRoleOk">
            <a-transfer
                    v-model:target-keys="roleTargetKeys"
                    :data-source="roleList"
                    :list-style="{width: '250px',height: '300px'}"
                    :operations="['担任', '取消']"
                    :render="item => `${item.name}`"
                    :rowKey="item => item.id">
                <template #notFoundContent>
                    <span>没数据</span>
                </template>
            </a-transfer>
        </a-modal>
    </div>
</template>

<script>
    import {ref, onMounted, reactive} from 'vue'
    import axios from 'axios'
    import {message} from 'ant-design-vue';

    export default {
        name: "system-user",
        setup() {
            const columns = [
                {
                    title: '头像',
                    dataIndex: 'headPicture',
                    key: 'headPicture',
                    slots: {customRender: 'headPicture'}
                },
                {
                    title: '账号',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '用户名',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '所属机构',
                    dataIndex: 'officeName',
                    key: 'officeName',
                },
                {
                    title: '电话',
                    dataIndex: 'phone',
                    key: 'phone',
                },
                {
                    title: '手机',
                    dataIndex: 'mobile',
                    key: 'mobile',
                },
                {
                    title: '用户类型',
                    dataIndex: 'userType',
                    key: 'userType',
                    slots: {customRender: 'userType'}
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    align: 'center'
                }
            ]

            const user = ref({})
            const userList = ref([])
            const officeList = ref([])
            const roleList = ref([])
            const roleTargetKeys = ref([])
            const searchData = ref({})
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })

            const visible = ref(false);
            const roleModalVisible = ref(false);

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/sys-user/list', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        name: searchData.value.name,
                        officeId: searchData.value.officeId,
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    userList.value = rs.data.data.records
                    pagination.value.total = rs.data.data.total
                })
            }

            const rest = () => {
                searchData.value = {}
                load()
            }

            const handlerChange = (pageInfo) => {
                pagination.value = pageInfo
                load()
            }

            const openModal = (obj) => {
                console.log("模态框参数：", obj)
                visible.value = true;
                user.value = JSON.parse(JSON.stringify(obj))
            }

            const handleOk = () => {
                axios.post('/sys-user/saveOrUpdate', user.value).then(rs => {
                    console.log("新增或修改结果：", rs)
                    if (rs.data.code == 200) {
                        visible.value = false
                        message.success("操作成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/sys-user/delete/' + id).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const openRoleModal = (sysRoles,userId) => {
                user.value.id = userId
                roleTargetKeys.value = []
                sysRoles.forEach(val=>{
                    roleTargetKeys.value.push(val.id)
                })
                roleModalVisible.value = true
            }

            const handleRoleOk = () =>{
                console.log("选中",roleTargetKeys.value)
                axios.post('/sys-role/assignRoles',{
                    userId: user.value.id,
                    roleIds: roleTargetKeys.value
                }).then(rs=>{
                    console.log(rs)
                    if (rs.data.code == 200){
                        message.success("用户角色更新成功")
                        roleModalVisible.value = false
                        load()
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            onMounted(() => {
                axios.get('/sys-office/queryAll').then(rs => {
                    officeList.value = rs.data.data
                })
                axios.get('/sys-role/queryAll').then(rs=>{
                    roleList.value = rs.data.data
                })
                load()
            })
            return {
                columns,
                user,
                userList,
                pagination,
                handlerChange,
                searchData,
                load,
                rest,
                openModal,
                visible,
                roleModalVisible,
                handleOk,
                okDelete,
                officeList,
                roleList,
                openRoleModal,
                roleTargetKeys,
                handleRoleOk
            }
        }
    }
</script>

<style scoped>

</style>